package encoder

import (
	"encoding/json"
	"github.com/go-kratos/kratos/v2/encoding"
	"google.golang.org/protobuf/proto"
	nethttp "net/http"
)

type Response struct {
	Code    int         `json:"code"`
	Reason  string      `json:"reason"`
	Message interface{} `json:"message"`
}

func RespEncoder(w nethttp.ResponseWriter, r *nethttp.Request, i interface{}) error {
	codec := encoding.GetCodec("json")
	messageMap := make(map[string]interface{})
	messageStr, _ := codec.Marshal(i.(proto.Message))
	_ = codec.Unmarshal(messageStr, &messageMap)

	// Notice 加上这行，如果返回的结果中只有一个key-value，会将结果的value单独放到message中
	// 举例：返回的message中的结果是：{"msg":"登陆了"},加上下面的代码会把"登陆了"放在"message"下面！
	//if len(messageMap) == 1 {
	//	for _, v := range messageMap {
	//		i = v
	//	}
	//}

	resp := Response{
		Code:   200,
		Reason: "",
	}

	if msg, ok := messageMap["message"]; ok {
		i = msg
	}

	message, err := codec.Marshal(i)
	_ = json.Unmarshal(message, &resp.Message)
	if err != nil {
		return err
	}

	data, err := codec.Marshal(resp)
	if err != nil {
		return err
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(data)
	return nil
}
